var price = 0;
function GroupResvListEditRoom(dom)
{
	var tr = dom.parents("tr:first");
	var roomtype = tr.find("[name='edit_res_detail_roomtype'] span");
	var room = tr.find("[name='edit_res_detail_rooms'] span");
	fillRoomDropdown(room,roomtype,tr,GroupResvListEditRoomSuccess);
}

function GroupResvListEditRoomSuccess(data,obj)
{
	var objArray = JSON.parse(data);
	var checkLogOut =  CheckSession(objArray);
	if(checkLogOut)
		return;
	if(objArray.EffectedRoom.length > 0)
	{
		//cerltimespan(savedSpan);
		closeWaitingDialog();
		finishChangeRoomDropDown(obj);
			
		for(var i=0;i<objArray.EffectedRoom.length;i++)
			changeRoom(objArray.EffectedRoom[i].id,objArray.EffectedRoom[i].roomId);
		DisplayDetail();
	}
	else
	{
		closeWaitingDialog();
		var msgDialog = $("#EmptyMessageDialog");
		simpleDialog(messagebox_MoveFail);
		//cerltimespan(savedSpan);
	}
}

function GroupResvListEditEmptyRoom(dom)
{
	var tr = dom.parents("tr:first");
	var roomtype = tr.find("[name='edit_res_detail_roomtype'] span");
	var room = tr.find("[name='edit_res_detail_rooms'] span");
	fillRoomDropdown(room,roomtype,tr,null,function(obj){
		var Tabs = getCurrentTabData();
		var priceRate =Tabs.ResData.priceRateString;
		var roomType=Tabs.ResData.roomtypeString;
		var pack = getObjectFromSharedData(SharedData.Package,priceRate);
		var price = getObjectFromDataIndex(pack.packagepriceList,"roomtypeString",roomType).priceperNight;
		var span = daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());
		var data = {
			func: "newResInGroup",
			roomtypeNew: obj.selectRoomType.find(":selected").val(),
			roomNew: obj.selectRoom.find(":selected").val(),
			roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title","Reserved Rooms").id,
			guestNameNew: "",
			guestLastNameNew: "",
			guestIdNew: 0,
			telNew: "",
			adultNew: 1,
			childNew: 0,
			packageNew: pack.id,
			priceNew: price*span,
			dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
			spanNew: span,
			groupIdNew: Tabs.resId,
			agencyId: 0
		};
		if(Tabs.resId != 0)
			simpleserviceWithArgs("/reservationService",data,GroupResvListEditEmptyRoomSuccess,obj);
		else
			EmptyGroupSelectRoom(obj);
		closeWaitingDialog();
	});
}

function GroupResvListEditEmptyRoomSuccess(data,obj){
	waitingDialog({});
	var objArray = JSON.parse(data);
	var checkLogOut =  CheckSession(objArray);
	if(checkLogOut)
		return;
	if(objArray.length > 0)
	{
		obj.domRoom.attr("roomid",obj.selectRoom.val());
		obj.domRoomType.attr("roomtypeid",obj.selectRoomType.val());
		obj.domRoom.text(obj.selectRoom.find(":selected").text());
		obj.domRoomType.text(obj.selectRoomType.find(":selected").text());
		
		cerltimespan(savedSpan);
		closeWaitingDialog();
		finishChangeRoomDropDown(obj);
		
		for(var i=0;i<objArray[0].length;i++)
			changeRoom(objArray[0][i].id,objArray[0][i].roomId);
		var Tabs = getCurrentTabData();
		var anotherObj = objArray[1];
		delete anotherObj["agencyIdString"];
		delete anotherObj["chargeListString"];
		delete anotherObj["creditString"];
		delete anotherObj["dateTo"];
		delete anotherObj["groupIdNumber"];
		delete anotherObj["groupIdString"];
		delete anotherObj["key"];
		delete anotherObj["packageByDateString"];
		delete anotherObj["paymentListString"];
		
		anotherObj.groupId = 0;
		anotherObj.otherCharge = 0;
		anotherObj.pay = 0;
		anotherObj.tax = 0;
		
		var pack = getObjectFromSharedData(SharedData.Package,objArray[1].packageByDate[0].packageString);
		anotherObj.priceRateName = pack.Name;
		anotherObj.priceRateString = objArray[1].packageByDate[0].packageString;
		anotherObj.reservationStatusName = getObjectFromSharedData(SharedData.ResvStatus,objArray[1].reservationStatusString).title;
		anotherObj.roomName = getObjectFromSharedData(SharedData.Room,objArray[1].roomString).roomName;
		anotherObj.roomTypeName = getObjectFromSharedData(SharedData.RoomType,objArray[1].roomTypeString).shortName;
		
		var tmp = {
			page: "Detail",
			type: "Single",
			resId: anotherObj.id,
			fromGroupId: Tabs.resId
		};
		tmp.ResData = anotherObj;
		tmp.ChargeList = anotherObj.chargeList;
		tmp.PaymentList = null;
		tmp.Task= null;
		tmp.guest= null;
		Tabs.GroupResvList.push(tmp);
		showResvList(Tabs);
	}
	else
		simpleDialog(messagebox_MoveFail,50,function() {cerltimespan(savedSpan)});
}

function EmptyGroupSelectRoom(obj)
{
	closeWaitingDialog();
	finishChangeRoomDropDown(obj);
	var Tabs = getCurrentTabData();
	if(Tabs.GroupResvList == null)
		Tabs.GroupResvList=[];
	for(var i=0;i<Tabs.GroupResvList.length;i++)
	{
		if(Tabs.GroupResvList[i].ResData.roomString == obj.selectRoom.val() )
		{
			simpleDialog(messagebox_MoveFail);
			return;
		}
	}
	obj.domRoom.attr("roomid",obj.selectRoom.val());
	obj.domRoomType.attr("roomtypeid",obj.selectRoomType.val());
	obj.domRoom.text(obj.selectRoom.find(":selected").text());
	obj.domRoomType.text(obj.selectRoomType.find(":selected").text());
	
	$(".command_button:visible [name=GrouptempReservation]").hide();
	var span = daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());
	for(var i=0;i<parseInt(Tabs.ResData.order);i++)
	{		
		var anotherObj ={};
		anotherObj.groupId = 0;
		anotherObj.otherCharge = 0;
		anotherObj.pay = 0;
		anotherObj.tax = 0;
		anotherObj.agencyId=0;
		anotherObj.span=span;
		anotherObj.guestNameNew= "";
		anotherObj.guestLastNameNew= "";
		anotherObj.guestIdNew= 0;
		anotherObj.telNew= "";
		anotherObj.adultNew= 1;
		anotherObj.childNew= 0;
		anotherObj.dateNew=$("#edit_res_resdetails_checkin").text().getDate().toSystemFormat();
		
		var pack = getObjectFromSharedData(SharedData.Package,Tabs.ResData.priceRateString);
		var roomType=Tabs.ResData.roomtypeString;
		var price = getObjectFromDataIndex(pack.packagepriceList,"roomtypeString",roomType).priceperNight;
		anotherObj.priceNew= price*span;
		anotherObj.priceRateName = pack.Name;
		anotherObj.priceRateString = Tabs.ResData.priceRateString;
		if($($("tr[refId="+(i+1)+"]").find($("td"))[3]).find("span").attr("roomid") == 0){break;}
		anotherObj.roomString=$($("tr[refId="+(i+1)+"]").find($("td"))[3]).find("span").attr("roomid");
		anotherObj.roomTypeString=$($("tr[refId="+(i+1)+"]").find($("td"))[2]).find("span").attr("roomtypeid");
		anotherObj.roomName = getObjectFromSharedData(SharedData.Room,anotherObj.roomString).roomName;
		anotherObj.roomTypeName = getObjectFromSharedData(SharedData.RoomType,anotherObj.roomTypeString).shortName;
		var tmp = {
				page: "Detail",
				type: "Single",
				resId: 0,
				fromGroupId: Tabs.resId
		};
		tmp.ResData = anotherObj;
		Tabs.GroupResvList[i]=tmp;
	}
}

function EmptyGroupBookRoom()
{
	$(".command_button:visible [name=GrouptempReservation]").hide();
	var Tabs = getCurrentTabData();
	if(Tabs.GroupResvList == null)
		return;
	for(var i=0;i<Tabs.GroupResvList.length;i++)
	{
		var obj={};
		obj.domRoomType=$($("tr[refId="+(i+1)+"]").find($("td"))[2]).find($("[name='edit_res_detail_roomtype'] span"));
		obj.domRoom=$($("tr[refId="+(i+1)+"]").find($("td"))[3]).find($("[name='edit_res_detail_rooms'] span"));
		obj.domRoom.attr("roomid",Tabs.GroupResvList[i].ResData.roomString);
		obj.domRoomType.attr("roomtypeid",Tabs.GroupResvList[i].ResData.roomTypeString);
		obj.domRoom.text(Tabs.GroupResvList[i].ResData.roomName);
		obj.domRoomType.text(Tabs.GroupResvList[i].ResData.roomTypeName);
	}
}

function AddReservation(el){
	
	if(!el.hasClass("active")) return;
	var Tabs = getCurrentTabData();
	var pack = getObjectFromSharedData(SharedData.Package,Tabs.ResData.priceRateString);
	var roomtype = getObjectFromSharedData(SharedData.RoomType,Tabs.ResData.roomtypeString);
	var price = getObjectFromDataIndex(pack.packagepriceList,"roomtypeString",Tabs.ResData.roomtypeString).priceperNight;
	
	
	var night = daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());


	var itemTemp = '<tr resId="{0}" from="{13}" to="{14}" refId="'+el.attr("refId")+'">' +
	'<td><div name="edit_res_detail_atcount">{1}<input type="checkbox" name="edit_res_detail_at"></div></td>' +
	'<td><div name="edit_res_detail_resid">{2}</div></td>' +
	'<td><div name="edit_res_detail_roomtype">{3}</div></td>' +
	'<td><div name="edit_res_detail_rooms">{4}</div></td>' +
	'<td><div name="edit_res_detail_guestname">{5}</div></td>' +
	'<td><div name="edit_res_detail_phone">{6}</div></td>' +
	'<td><div name="edit_res_detail_guestamount">{7}</div></td>' +
	'<td><div name="edit_res_detail_status">{8}</div></td>' +
	'<td><div name="edit_res_detail_checkinstatus">{9}</div></td>' +
	'<td><div name="edit_res_detail_night">{10}</div></td>' +
	'<td><div name="edit_res_detail_rate">{11}</div></td>' +
	'<td><div name="edit_res_detail_price">{12}</div></td>' +
	'</tr>';
	var totalPrice = 0;
	for(i=0;i<night;i++)
	{
		var tmp = calTax(price,i);
		totalPrice += (!SharedData.General.incloudetax)?tmp.costIncludeTax:tmp.costIncludeTax-tmp.tax;
	}
	$("#resvList").find("tr:last").after(itemTemp.format(
			0,
			$("#resvList").find("tr").length,
			"&nbsp;",
			"<span class='link' onclick='GroupResvListEditEmptyRoom($(this));' roomtypeid='"+roomtype.id+"'>"+roomtype.shortName+"</span>",
			"<span class='link' onclick='GroupResvListEditEmptyRoom($(this));' roomid='0'>"+simpleLabel_Select+"</span>",
			"&nbsp;",
			"&nbsp;",
			"1" + " - " + "0",
			"-",
			$("#edit_res_resdetails_checkin").text() + " - " + $("#edit_res_resdetails_checkout").text(),
			night,
			pack.Name,
			toCurrencyString(totalPrice),
			$("#edit_res_resdetails_checkin").text().getDate(),
			$("#edit_res_resdetails_checkout").text().getDate(),
			"&nbsp;",
			"&nbsp;"
		));
}

function calTax(cost,index,includeTax){
	var taxList = SharedData.RoomTax;
	if(includeTax == null) includeTax = SharedData.General.incloudetax;
	var returnValue = {};

	var price = cost;
	var tax = 0;
	if(!includeTax){
		for(var i=0;i<taxList.length;i++){
			if(taxList[i].IsOnRoomTariff)
					tax += cost * (taxList[i].CurrencyValue/100);
				else if(taxList[i].IsPerReservation && index == 0)
					tax += taxList[i].CurrencyValue;	
				else if(taxList[i].IsPerNight)
					tax += taxList[i].CurrencyValue;
			}
			returnValue.costIncludeTax = (price + tax);
			returnValue.tax = tax;
			return returnValue;
	}
	else{
		var k = 0;
		var perc = 0;
		for(var i =0;i<taxList.length;i++){
			if(taxList[i].IsOnRoomTariff)
				perc += taxList.get(i).getCurrencyValue();
			else if(taxList[i].IsPerReservation && index == 0)
				k += taxList[i].CurrencyValue;	
			else if(taxList[i].IsPerNight)
				k += taxList[i].CurrencyValue;
		}
			
		var x_realprice = ((cost-k)*100) / (100+perc);
		tax = ((perc * x_realprice)/100) + k;
			
		returnValue.costIncludeTax = price;
		returnValue.tax = tax;
		return returnValue;
	}
}

function checkedAll(){
	var addRoomDetail = $(".addNewRoom").css("display");
	if(addRoomDetail=="none"){
		if($('#resvList tr [type=checkbox]')[0].checked == true){
			for(var i = 1;i<$('#resvList tr [type=checkbox]').length-1;i++)
				$('#resvList tr [type=checkbox]')[i].checked = true;
		}else{
			for(var i = 1;i<$('#resvList tr [type=checkbox]').length-1;i++)
				$('#resvList tr [type=checkbox]')[i].checked = false;
		}
	}else{
		if($('#resvList tr [type=checkbox]')[0].checked == true){
			for(var i = 0;i<$('#resvList tr [type=checkbox]').length;i++)
				$('#resvList tr [type=checkbox]')[i].checked = true;
		}else{
			for(var i = 0;i<$('#resvList tr [type=checkbox]').length;i++)
				$('#resvList tr [type=checkbox]')[i].checked = false;
		}
	}
	
}

function calPrice(){
	if($('#edit_res_detail_adult3').val() == null){
		var nowAdult = $('#adult3').val();
		var nowChild = $('#child3').val();
		var roomtypeChose = roomtypeId;
		if($('#SeasonalRate').attr("disabled") == null){
			var nowPriceRate = $('#SeasonalRate').val();
		}else{
			var nowPriceRate = $('#SeasonalRate3').val();
		}
		var nowSpan = span;
	}else{
		var nowAdult = $('#edit_res_detail_adult3').val();
		var nowChild = $('#edit_res_detail_child3').val();
		var roomtypeChose = $('#edit_res_roomtype_cb').val();
		var nowPriceRate = $('#edit_res_rate_cb').val();
		var nowSpan = $('#edit_res_detail_night').html();
	}
	
	var link = "/packageService?doClass=getChildExBed&packageId=" + nowPriceRate
	+ "&roomtype=" + roomtypeChose + "&occA=" + nowAdult + "&occC=" + nowChild;
	simpleservice(link,null,function(data){
		var objArray = JSON.parse(data);
		$('#edit_res_detail_price').html(objArray*nowSpan);
	});
}

function calSpan(){
	if($('#edit_res_detail_checkinstatus').attr('value') == null){
		var checkin = $('#edit_res_detail_checkinstatus').attr('dateofres');
	}else{
		var checkin = $('#edit_res_detail_checkinstatus').attr('value');
	}
	if($('#edit_res_detail_checkoutstatus').attr('value') == null){
		var checkin = $('#edit_res_detail_checkoutstatus').attr('dateofres');
	}else{
		var checkout = $('#edit_res_detail_checkoutstatus').attr('value');
	}
	var checkinArray = checkin.split("-");
	var checkoutArray = checkout.split("-");
	var dateCheckIn = new Date(checkinArray[0],checkinArray[1] - 1,checkinArray[2]);
	var dateCheckOut = new Date(checkoutArray[0],checkoutArray[1] - 1,checkoutArray[2]);
	var soSpan = (dateCheckOut - dateCheckIn)/86400000;
	$('#edit_res_detail_night').html(soSpan);
	calPrice();
}

function CloseAllPopup(id)
{
	if(id == "editres-addroom-close"||id == "editres-addroom-bt-cancel")
		$("#editres-addguest-addroom").css("display","none");
	if(id == "editres-deleteroom-close"||id == "editres-deleteroom-bt-cancel")
		$("#alert-popup-delete-room").css("display","none");
}

